﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using AMM.Business;
using AMM.Business.Store;
using AMM.CustomWinControls;
using AMM.Model;
using AMM.Model.Store;
using AMM.UserControls;
using Microsoft.Reporting.WinForms;

namespace AMM.Forms.Store {
    public partial class FrmOutsourceOrder : FrmOutsourceOrderBase {

        private int _pageIndex;
        private OutsourceOrderSearchModel _searchModel;
        private OutsourceOrderProcessor _outsourceOrderProcessor;
        private List<OutsourceOrderViewModel> _outsourceOrderList;

        #region Override

        protected override string FunctionCode {
            get { return "AMM1203"; }
        }

        protected override BaseSearchControl SearchControl {
            get { return new OutsourceOrderSearchControl(); }
        }

        protected override void Add() {
            this.ResetForms();
            this.ShowEditForm("新增", new OutsourceOrder() { ClassStatus = ClassStatus.Added });
            base.Add();
        }

        protected override void Amend() {
            List<OutsourceOrderViewModel> selectedList = this.dgvOutsourceOrderList.GetSelectedRows<OutsourceOrderViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            OutsourceOrder outsourceOrder = this._outsourceOrderProcessor.FetchOutsourceOrderById(selectedList[0].Key);
            outsourceOrder.ClassStatus = ClassStatus.Updated;
            if ((AuditStatus)outsourceOrder.Status == AuditStatus.Audited) {
                this.ShowInfo("审核的订单不能被修改！");
                return;
            }
            this.ShowEditForm("修改", outsourceOrder);
            base.Amend();
        }

        protected override void Save() {
            base.Save();
        }

        protected override void Delete() {
            List<OutsourceOrderViewModel> selectedList = this.dgvOutsourceOrderList.GetSelectedRows<OutsourceOrderViewModel>();
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._outsourceOrderProcessor.Delete(selectedList.Select(x => x.Key).ToArray());
                this.MDIParent.SetStatusInformation("删除成功");
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                base.Delete();
            });
        }

        protected override void Audit() {
            List<OutsourceOrderViewModel> selectedList = this.dgvOutsourceOrderList.GetSelectedRows<OutsourceOrderViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                string resultMsg = string.Empty;
                OutsourceOrder outsourceOrder = this._outsourceOrderProcessor.FetchOutsourceOrderById(selectedList[0].Key);
                if (outsourceOrder.Status == (int)AuditStatus.Audited) {
                    if (this.ShowQuestion("订单已经通过审核，确定将取消审核状态！") == DialogResult.No) { return; }
                    outsourceOrder.Status = (int)AuditStatus.Waiting;
                    resultMsg = "取消审核成功";
                }
                else {
                    outsourceOrder.Status = (int)AuditStatus.Audited;
                    resultMsg = "审核成功";
                }                
                outsourceOrder.AuditedBy = LoginUserName;
                this._outsourceOrderProcessor.Audit(outsourceOrder);
                this.MDIParent.SetStatusInformation(resultMsg);
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                base.Audit();
            });
        }

        protected override void Print() {
            List<OutsourceOrderViewModel> selectedList = this.dgvOutsourceOrderList.GetSelectedRows<OutsourceOrderViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PrintHelperIns = new PrintHelper("OutsourceOrderPrint.rdlc", this.Text);
                this.PrintHelperIns.ReportDataSources.Add(new ReportDataSource("ds", selectedList));
                base.Print();
            }, () => {
                // for hiding
                this.PrintHelperIns.Dispose();
            });
        }

        protected override void Search(object sender, FrmSearch.SearchArgs e) {
            this.CreateNewThread(() => {
                if (e.IsRevert) {
                    this._searchModel = new OutsourceOrderSearchModel();
                }
                else {
                    this._searchModel = (OutsourceOrderSearchModel)e.SearchModel;
                }
            }, () => {
                this.BindOutsourceOrderList();
            });
        }

        #endregion

        public FrmOutsourceOrder() {
            InitializeComponent();

            this.dgvOutsourceOrderList.DataGridViewModelType = typeof(OutsourceOrderViewModel);
            this.dgvOutsourceOrderDetailList.DataGridViewModelType = typeof(OutsourceOrderDetailsViewModel);
        }

        #region Private methods

        private bool frmEdit_Edit(object sender, FrmEdit.EditArgs e) {
            bool resultFlag = false;
            OutsourceOrder outsourceOrder = (OutsourceOrder)e.EditModel;
            if (outsourceOrder.OutsourceOrderDetails.Count == 0) {
                this.ShowError("请添加订单明细记录！");
                return false;
            }
            this.PreventCancel = true;
            this.CreateNewThread(() => {
                if (outsourceOrder.ClassStatus == ClassStatus.Added) {
                    outsourceOrder.CreatedBy = LoginUserName;
                    this._outsourceOrderProcessor.Insert(outsourceOrder);
                }
                else {
                    outsourceOrder.ModifiedBy = LoginUserName;
                    this._outsourceOrderProcessor.Update(outsourceOrder);
                }
                resultFlag = true;
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                if (resultFlag) {
                    this.MDIParent.SetStatusInformation("保存成功");
                    this.FormEdit.Close();
                }
            });

            this.Save();
            return true;
        }

        private void ResetForms() {
            this.BindOutsourceOrderList();
            this.BindOutsourceOrderDetailsList(0);
        }

        private void BindOutsourceOrderList() {
            this.CreateNewThread(() => {
                this._outsourceOrderList = this._outsourceOrderProcessor.FetchOutsourceOrderViewModelList(this._searchModel, this._pageIndex);
            }, () => {
                this.dgvOutsourceOrderList.DataSource = new SortableBindingList<OutsourceOrderViewModel>(this._outsourceOrderList);
                this.pceList.Records = this._searchModel.Records;
                this.pceList.DataBind();
            });
        }

        private void BindOutsourceOrderDetailsList(int outsourceId) {
            List<OutsourceOrderDetailsViewModel> detailsList = new List<OutsourceOrderDetailsViewModel>();
            this.CreateNewThread(() => {
                if (outsourceId != 0) {
                    detailsList = this._outsourceOrderProcessor.FetchOutsourceOrderDetailsViewModelList(outsourceId);
                }
            }, () => {
                this.dgvOutsourceOrderDetailList.DataSource = new SortableBindingList<OutsourceOrderDetailsViewModel>(detailsList);
            });
        }

        private void ShowEditForm(string title, OutsourceOrder outsourceOrder) {
            this.CreateNewThread(() => {
                Thread.Sleep(100);
            }, () => {
                OutsourceOrderEditControl editControl = new OutsourceOrderEditControl();
                this.FormEdit = new FrmEdit();
                editControl.BaseEditModel = outsourceOrder;
                editControl.ValidatorForEdit = this.FormEdit.validatorForEdit;
                this.FormEdit.Controls.Add(editControl);
                this.FormEdit.Edit += new FrmEdit.EditEventHandler(frmEdit_Edit);
                this.FormEdit.Text = string.Format("{0}{1}", title, this.Text);
                FrmEntry.LoadAndRunDialog(this.FormEdit);
            });
        }

        #endregion

        private void FrmOutsourceOrder_Load(object sender, EventArgs e) {
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._outsourceOrderProcessor = new OutsourceOrderProcessor(this.pceList.PageSize);
                this._searchModel = new OutsourceOrderSearchModel();
                this._pageIndex = 1;
            }, () => {
                this.WindowState = FormWindowState.Maximized;
                this.ResetForms();
                this.PreventCancel = false;
            });
        }

        private void pceList_Paging(object sender, PaginationArgs e) {
            this._pageIndex = e.PageIndex;
            this.BindOutsourceOrderList();
        }

        private void dgvOutsourceOrderList_DoubleClick(object sender, EventArgs e) {
            if (this.dgvOutsourceOrderList.CurrentRow != null) {
                int outsourceId = (int)this.dgvOutsourceOrderList.CurrentRow.Cells["Key"].Value;
                this.BindOutsourceOrderDetailsList(outsourceId);
            }
        }
    }
}
